package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.khotyn.heresy.exception.NullCollectionException;
import com.khotyn.heresy.exception.NullPictureException;
import com.khotyn.heresy.exception.PermissionException;
import com.khotyn.heresy.exception.ReCollectException;
import com.khotyn.heresy.service.FavouriteService;

/**
 * 收藏图片控制器
 * 可以进行添加和删除收藏的操作
 * URI:addFavourite.html(添加收藏)
 * URI:delFavourite.html(删除收藏)
 * @author 金灵杰
 *
 */
@Controller
@SessionAttributes("userID")
public class FavouriteController {
	@Autowired
	private FavouriteService favouriteService;
	
	/**
	 * 绑定添加收藏链接，通过FavouriteService服务添加收藏
	 * @param uid 用户id
	 * @param pid 图片id
	 * @param response 返回处理状态
	 */
	@RequestMapping("/addFavourite.html")
	public void addFavourite(@ModelAttribute("userID") int uid, 
			@RequestParam(value = "pid", required=false) String pid, HttpServletResponse response)
	{
		try {
			favouriteService.addFavouriteSerivce(uid, pid);
			response.setStatus(HttpServletResponse.SC_CREATED);			//响应代码201
		} catch (NullPictureException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);	//响应代码400
		} catch (PermissionException e) {
			response.setStatus(HttpServletResponse.SC_FORBIDDEN);		//响应代码403
		} catch (ReCollectException e) {
			response.setStatus(HttpServletResponse.SC_CONFLICT);		//响应代码409
		}
	}
	
	/**
	 * 绑定删除收藏链接，通过FavouriteService服务删除收藏
	 * @param uid 用户id
	 * @param cid 收藏id
	 * @param response 返回处理状态
	 */
	@RequestMapping("/delFavourite.html")
	public void delFavourite(@ModelAttribute("userID") int uid,
			@RequestParam(value = "cid", required = false) String cid, HttpServletResponse response)
	{
		try {
			favouriteService.delFavouriteService(uid, cid);
			response.setStatus(HttpServletResponse.SC_OK);				//响应代码200
		} catch (NullCollectionException e) {
			response.setStatus(HttpServletResponse.SC_NOT_FOUND);		//响应代码404
		} catch (NumberFormatException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);	//响应代码400
		}
	}

	/**
	 * @param favouriteService the favouriteService to set
	 */
	public void setFavouriteService(FavouriteService favouriteService) {
		this.favouriteService = favouriteService;
	}
}
